package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.mapper.CommentRqMapper;
import com.yupi.springbootinit.model.entity.Comment;
import com.yupi.springbootinit.model.entity.CommentRq;
import com.yupi.springbootinit.model.vo.CommentVO;
import com.yupi.springbootinit.service.CommentService;
import com.yupi.springbootinit.mapper.CommentMapper;
import com.yupi.springbootinit.utils.ThumbNailUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
* @author LENOVO
* @description 针对表【comment(评论)】的数据库操作Service实现
* @createDate 2024-09-18 08:40:59
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{

    /**
     *
     *
     * */

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private CommentRqMapper commentRqMapper;
    /**
     * 获取评论
     * @param postid
     * @return
     */
    @Override
    public List<CommentVO> getComment(Long postid) {

        List<CommentVO> resultCommentList = new ArrayList<>();

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("postId",postid);
        queryWrapper.eq("isDelete",0);
        List<Comment> postComment = commentMapper.selectList(queryWrapper);
        if (postComment == null){
            return null;
        }
        for (int i = 0; i < postComment.size(); i++) {
            Comment comment = postComment.get(i);

            Long id = comment.getId();
            Long postId = comment.getPostId();
            String content = comment.getContent();
            Long userId = comment.getUserId();
            Date createTime = comment.getCreateTime();
            Date updateTime = comment.getUpdateTime();
            Integer isDelete = comment.getIsDelete();
            Integer anon = comment.getAnon();
            String anonName = comment.getAnon_name();
            String imgpath = comment.getImgpath();

            CommentVO commentVO = new CommentVO();
            commentVO.setId(id);
            commentVO.setPostId(postId);
            commentVO.setContent(content);
            commentVO.setUserId(userId);
            commentVO.setCreateTime(createTime);
            commentVO.setUpdateTime(updateTime);
            commentVO.setIsDelete(isDelete);
            commentVO.setAnon(anon);
            commentVO.setAnon_name(anonName);
            commentVO.setImgpath(imgpath);

            QueryWrapper<CommentRq> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("commentId",id);
            queryWrapper1.eq("isDelete",0);
            List<CommentRq> commentRqList = commentRqMapper.selectList(queryWrapper1);


            commentVO.setChildrenComments(commentRqList);


            resultCommentList.add(commentVO);


        }
        return resultCommentList;

    }

    @Override
    public void validComment(Comment comment, boolean add) {
        if (comment == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String content = comment.getContent();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(content), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        List<String> sensitiveWords = Arrays.asList(// 违反法律法规类
                "法轮功", "全能神", "华藏宗门", "冰毒", "海洛因", "大麻", "制毒", "贩毒", "P2P暴雷", "虚拟货币挖矿", "民间标会倒会", "套路贷",
                // 危害国家安全与社会稳定类
                "港独", "台独", "蒙独", "疆独", "反动会道门", "恶意诋毁国家政策", "抹黑医保改革", "唱衰国企",
                // 低俗色情类
                "阴茎", "睾丸", "阴道", "阴蒂", "做爱", "性交", "口交", "肛交", "自慰", "一夜情", "嫖娼", "约炮", "乳沟", "翘臀", "丝袜诱惑",
                "苍井空", "波多野结衣", "小泽玛利亚", "武藤兰", "AV女优", "成人影片", "三级片", "黄片", "色情直播", "裸聊", "露点", "性感内衣秀",
                "性癖好", "性虐待", "SM", "淫荡", "风骚", "狐狸精", "荡妇", "牛郎", "鸭店", "色情按摩", "情趣用品",
                "AV", "ML", "FJ", "KJ", "约P", "PC", "黄播", "色Q",
                // 暴力恐怖类
                "基地组织", "伊斯兰国", "博科圣地", "斩首", "肢解", "枪杀", "纵火", "爆炸", "绑架勒索", "持械抢劫",
                // 网络诈骗类
                "刷单返现骗局", "网络兼职诈骗", "冒充公检法诈骗", "交友杀猪盘", "荐股诈骗", "跑分", "赌博", "彩票",
                // 知识产权侵权类
                "山寨苹果手机", "假耐克运动鞋", "盗版微软系统", "未经授权翻拍某电影", "盗版某热门小说", "盗录某演唱会音频",
                // 人身攻击与歧视类
                "黑鬼", "白皮猪", "男尊女卑", "女权癌", "娘炮", "弱女子", "瘸子", "瞎子", "聋子", "弱智",
                // 不实信息与谣言类
                "某地发生9级地震", "某明星去世", "吃绿豆治百病", "喝醋软化血管", "永动机研发成功", "量子速读提升学习能力",
                // 广告垃圾信息类
                "特效抗癌药", "根治糖尿病神药", "一周瘦十斤减肥药", "三个月长高10厘米增高药", "加微信免费领礼品", "点击链接获取巨额奖金"); // 示例敏感词列表
        if (containsSensitiveWords(content, sensitiveWords)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容包含敏感词");
        }
    }

    /**
     * 判断文本是否包含敏感词
     * @param text
     * @param sensitiveWords
     * @return
     */
    private boolean containsSensitiveWords(String text, List<String> sensitiveWords) {
        if (StringUtils.isBlank(text)) {
            return false;
        }
        for (String word : sensitiveWords) {
            if (text.contains(word)) {
                return true;
            }
        }
        return false;
    }

    @Value("${commentFilePath}")
    private String commentImgPath;
    @Override
    public List<String> uploadImage(List<MultipartFile> files) {
        List<String> fileNames = new ArrayList<>();

        for (MultipartFile file : files) {
            String imageName = file.getOriginalFilename();
            if (imageName == null || imageName.isEmpty()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }

            String[] split = imageName.split("\\.");
            String imgType = split[split.length - 1];
            UUID randomUUID = UUID.randomUUID();
            String fileName = randomUUID + "." + imgType;
            String filePath = commentImgPath + fileName;
            ThumbNailUtil.thumbnail(file, filePath,imgType);
            fileNames.add(fileName);
        }
        return fileNames;
    }

    @Override
    public boolean deleteCommentImage(String fileName) {
        String[] filenames = StringUtils.split(",", fileName);
        for ( String filename: filenames) {
            String filePath = commentImgPath + filename;

            File imageFile = new File(filePath);
            if (imageFile.exists()) {
                boolean success = imageFile.delete();
                if(!success) {
                    throw  new BusinessException(ErrorCode.SYSTEM_ERROR,"删除图片失败");
                }
            } else {
                throw  new BusinessException(ErrorCode.PARAMS_ERROR,"图片不存在");
            }
        }
        return true;
    }

    @Override
    public boolean deleteOldComment(Long postId) {

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("postId", postId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        for ( Comment comment:comments) {
            String imgpath = comment.getImgpath();
            if (StringUtils.isNotBlank(imgpath)) {
                this.deleteCommentImage(imgpath);
            }
            int delete = commentMapper.deleteOldCommentById(comment.getId());

            if (delete < 0) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"删除旧评论失败");
            }
        }

        return true;

    }
}




